package com.mine.control;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;

import com.mine.util.FormatReport;
import com.mysql.jdbc.DatabaseMetaData;

public class ControlTable {
	private static Connection con;
	static {
		try {
			con = ConnectMYSQL.connectMySql();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void createTable(String tableName) throws Exception {
		Statement s = con.createStatement();
		s
				.execute("create table "
						+ tableName
						+ " (id int auto_increment primary key,testcase varchar(255),status varchar(20),time varchar(20))");
	}
	
	public static boolean searchTable(String tableName) throws SQLException{
		DatabaseMetaData meta = (DatabaseMetaData) con.getMetaData();
		ResultSet ret = meta.getTables(null, null, tableName, null); 
		boolean isexit = false;
		while(ret.next()){
			isexit = true;
		}
		return isexit;
	}
		
	public static void inputTargerTable(String path, String tableName , String type)
			throws Exception {
		Statement s = con.createStatement();
		ArrayList<String[]> al = FormatReport.formatReport(path, type);
		for (String[] result : al) {
			s.execute("insert into " + tableName
					+ " (testcase,status,time) values ('" + result[0] + "','"
					+ result[1] + "','" + result[2] + "')");
		}

		System.out.println(al.isEmpty());
	}

	public static void dropTargerTable(String tableName) {
		try {
			Statement s = con.createStatement();
			s.execute("drop table " + tableName);
		} catch (SQLException e) {
		}
	}

	public static ResultSet selectTargetTable(String tableName, String testcase) {
		Statement s;
		try {
			s = con.createStatement();
			ResultSet rs = s.executeQuery("select * from " + tableName
					+ " where testcase like '" + testcase + "'");
			rs.next();
			return rs;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
}
